import { Component, OnInit, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { CmModalService, ModalParams } from "./modal.service";

/**
 * 模态框组件
 * 
 * @export
 * @class CmModalComponent
 * @implements {OnInit}
 */
@Component({
  selector: 'cm-modal-instance',
  templateUrl: 'modal-instance.component.html',
  styleUrls: ['modal-instance.component.less'],
  inputs: [
    "justTip",
    "tips",
    "heading",
    "dataObs",
    "params"
  ],
  outputs: [
    "onClickOk",
    "onClickCancel"
  ]
})
export class CmModalInstanceComponent implements OnInit {
  params: ModalParams;
  closeObserver;
  dataOps: Observable<any>; //透过模态框传递的Observable数据
  justTip: boolean = false; //是否仅仅是提示框，仅提示框无Cancel按钮，只显示OK
  onClickOk = new EventEmitter();
  onClickCancel = new EventEmitter();

  constructor(private service: CmModalService) {

  }

  ngOnInit() {
    console.debug("Modal: ", this);

    // enter事件
    Observable.fromEvent(window, "keydown").subscribe((e: KeyboardEvent) => {
      if (e.key === "Enter") {
        if (this.justTip) {
          this.close(false);
        } else {
          this.close(true);
        }
      }
    });
  }

  close(isOk: boolean) {
    let feedback = {
      data: this.params.data,
      isOk
    };
    this.params.closeObserver.next(feedback);
    isOk ? this.onClickOk.emit(this.dataOps) : this.onClickCancel.emit(this.dataOps);
  }

}

const getDynamicModal = (templateUrl, moduleId) => {
  console.debug("MODAL TEMPLATE: ", templateUrl);
  @Component({
    // moduleId, //webpack木有
    templateUrl,
    styleUrls: [

    ],
    inputs: [
      "justTip",
      "tips",
      "heading",
      "dataObs",
      "params"
    ],
    outputs: [
      "onClickOk",
      "onClickCancel"
    ]
  })
  class DynamicModalInstanceComponent implements OnInit {
    params: ModalParams;
    closeObserver;
    dataOps: Observable<any>;
    tips: string[];
    justTip: boolean = false;
    onClickOk = new EventEmitter();
    onClickCancel = new EventEmitter();

    constructor(private service: CmModalService) {

    }

    ngOnInit() {
      // enter事件
      Observable.fromEvent(window, "keydown").subscribe((e: KeyboardEvent) => {
        if (e.key === "Enter") {
          if (this.justTip) {
            this.close(false);
          } else {
            this.close(true);
          }
        }
      });
    }

    close(isOk: boolean) {
      let feedback = {
        data: this.params.data,
        isOk
      };
      this.params.closeObserver.next(feedback);
      isOk ? this.onClickOk.emit(this.dataOps) : this.onClickCancel.emit(this.dataOps);
    }

  }

  return DynamicModalInstanceComponent;
}

export { getDynamicModal };